import React,{ useState } from 'react'
import { Redirect } from 'react-router-dom';
import { Form, Input, Button,message } from 'antd';
import { UserOutlined,LockOutlined } from '@ant-design/icons';
import { connect } from 'react-redux';
import { reqLogin } from '../../api'
import { saveUser } from '../../utils/storageUtils';
import { setUser } from '../../redux/actions';
import './Login.css'

export default connect((state)=>({user:state.user}),{setUser})(function Login(props) {

  const [isLogin,setIsLogin]=useState(false)
  const { history,setUser,user } =props

  if(user._id){
    message.success('自动登录')
    return <Redirect to="/home"/>
  }

  const onFinish=async (values)=>{
    const { username,password } = values
    setIsLogin(true)
    let res= await reqLogin(username,password,()=>setIsLogin(false))
    if(res.code!==200){
      message.error(res.msg)
    }else{
      let roles=await require('../../api').reqRoles()
      let menus=roles.find(i=>i._id===res.data.role_id).menus
      res.data.menus=menus
      setUser(res.data)
      saveUser(res.data)
      history.replace('/home')
      message.success(res.msg)
    }
  }

  const onFinishFailed=(values)=>{
    let { errorFields }=values
    errorFields.forEach(e=>message.warn(e.errors[0]))
  }



  return (
    <div className='login'>
      <header>
        <h1>后台管理系统</h1>
      </header>
      <section className='login-from'>
        <h2>用户登录</h2>
        <Form
          name="normal_login"
          className="login-form"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item name="username" 
          rules={[
            { required: true, message: '请输入你的用户名!' },
            { min: 4,max: 12, message: '用户名至少4位,至多12位!' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名必须由英文、数字或下划线组成' }
            ]}>
            <Input className="username-input" prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
          </Form.Item>

          <Form.Item name="password" 
          rules={[
            { required: true,whitespace:true, message: '请输入你的密码!' },
            { min: 6,max: 20, message: '密码至少6位,至多20位!' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '密码必须由英文、数字或下划线组成' }
            ]}>
            <Input className="password-input" prefix={<LockOutlined className="site-form-item-icon" />} type="password" placeholder="密码"/>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-button" loading={isLogin}>
              Log in
            </Button>
          </Form.Item>
        </Form>
      </section>
      <footer></footer>
    </div>
  )
})
